import { LC_USERTOKEN } from '@/global/constant'
import { login as requestLogin, getInfo, getMenus } from '@/service/modules/app'
import type { LoginForm, Menu, UserModel } from '@/types'
import CacheService from '@/utils/cache'
import { defineStore } from 'pinia'

interface appStoreState {
  token: string
  userInfo: UserModel
  userMenus: Menu[]
  homePagePath: string
}

const useAppStore = defineStore('app', {
  state: (): appStoreState => ({
    token: CacheService.getItem(LC_USERTOKEN) ?? '',
    homePagePath: '',
    userInfo: {
      id: 0,
      username: '',
      email: '',
      avatar: '',
      nickname: '',
      role_id: 0,
      dept_id: 0,
      status: 0,
      created_time: new Date(),
      updated_time: new Date(),
    },
    userMenus: [],
  }),
  actions: {
    // 登录
    login(loginForm: LoginForm) {
      return new Promise(async (resolve, reject) => {
        try {
          const { data: result } = await requestLogin(loginForm)
          this.token = result.token
          CacheService.setItem(LC_USERTOKEN, result.token)
          resolve(result)
        } catch (error) {
          reject(reject)
        }
      })
    },
    // 获取登录用户信息
    getUserInfo() {
      return new Promise(async (resolve, reject) => {
        try {
          const { data: userInfo } = await getInfo()
          this.userInfo = userInfo
          resolve(userInfo)
        } catch (error) {
          reject(reject)
        }
      })
    },
    // 获取登录用户权限菜单
    getUserMenus() {
      return new Promise(async (resolve, reject) => {
        try {
          const { data: userMenus } = await getMenus()
          this.userMenus = userMenus
          this.homePagePath = userMenus[0]?.route
          resolve(userMenus)
        } catch (error) {
          reject(reject)
        }
      })
    },
    // 退出登陆
    logout() {
      return new Promise((resolve, reject) => {
        try {
          this.token = ''
          this.userInfo = {
            id: 0,
            username: '',
            email: '',
            avatar: '',
            nickname: '',
            role_id: 0,
            dept_id: 0,
            status: 0,
            created_time: new Date(),
            updated_time: new Date(),
          }
          this.userMenus = []
          CacheService.removeItem(LC_USERTOKEN)
          resolve(true)
        } catch (error) {
          resolve(error)
        }
      })
    },
  },
})

export default useAppStore
